package com.cockatiel.statemachine.cola.statemachine;

import com.alibaba.cola.statemachine.builder.StateMachineBuilder;
import com.alibaba.cola.statemachine.builder.StateMachineBuilderFactory;
import com.cockatiel.statemachine.cola.statemachine.service.StatusAction;
import com.cockatiel.statemachine.cola.statemachine.service.StatusCondition;
import com.cockatiel.statemachine.enums.ActivityEvent;
import com.cockatiel.statemachine.enums.ActivityState;
import com.cockatiel.statemachine.enums.ChannelTypeEnum;
import com.cockatiel.statemachine.model.StatemachineContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Created By Intellij IDEA
 *
 * @Author: louxiujun@kanzhun.com
 * @Date: 2023-06-11 08:55:09
 * @Description:
 */
@Component
@Slf4j
public class SmsStateMachine implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    @Qualifier("smsStatusAction")
    private StatusAction smsStatusAction;

    @Autowired
    @Qualifier("smsStatusCondition")
    private StatusCondition smsStatusCondition;

    // 基于DSL构建状态配置，触发事件转移和后续的动作
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 第一步：生成一个状态机builder
        StateMachineBuilder<ActivityState, ActivityEvent, StatemachineContext> builder = StateMachineBuilderFactory.create();

        // 第二步：设置一个外部状态转移类型的builder，并设置from\to\on\when\perform
        builder.externalTransition()
                .from(ActivityState.NOT_START)
                .to(ActivityState.DATA_PREPARING)
                .on(ActivityEvent.ACT_BEGIN)
                .when(smsStatusCondition.checkCondition())
                .perform(smsStatusAction.doAction()); //这个action 我们可以按自己所需修改，比如这种Action<R,T> service的方法Service::method
        builder.externalTransition()
                .from(ActivityState.DATA_PREPARING)
                .to(ActivityState.DATA_PREPARED)
                .on(ActivityEvent.FINISH_DATA_CAL)
                .when(smsStatusCondition.checkCondition())
                .perform(smsStatusAction.doAction());
        // ...(此处省略其他状态流转的装配)

        // 第三步：设置状态机的id和ready，并在StateMachineFactory中的stateMachineMap进行注册
        builder.build(StatusMachineEngine.getMachineEngine(ChannelTypeEnum.SMS));
    }
}
